﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace MVCExtension.FrameWork
{
    /// <summary>
    /// HttpContex系列操作，Cookie读写操作
    /// </summary>
    public class RequestHelper
    {
        /// <summary>
        /// 获取当前的HttpContext
        /// </summary>
        /// <returns></returns>
        public static HttpContext HttpContext
        {
            get { return System.Web.HttpContext.Current; }
        }
        public static HttpRequest Request
        {
            get { return System.Web.HttpContext.Current.Request; }
        }
         /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        public static string GetMapPath(string strPath)
        {
            if (HttpContext.Current != null)
            {
                return HttpContext.Current.Server.MapPath(strPath);
            }
            else //非web程序引用
            {
                strPath = strPath.Replace("/", "\\");
                if (strPath.StartsWith("\\"))
                {
                    strPath = strPath.Substring(1);
                }
                return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
            }
        }
        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string GetHost()
        {
            return HttpContext.Current.Request.Url.Host;
        }
        /// <summary>
        /// 获取当前请求的原始 URL(URL 中域信息之后的部分,包括查询字符串(如果存在))
        /// </summary>
        /// <returns>原始 URL</returns>
        public static string GetRawUrl()
        {
            return HttpContext.Current.Request.RawUrl;
        }
        /// <summary>
        /// 得到当前完整主机头
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentFullHost()
        {
            HttpRequest request = System.Web.HttpContext.Current.Request;
            if (!request.Url.IsDefaultPort)
            {
                return string.Format("{0}:{1}", request.Url.Host, request.Url.Port.ToString());
            }
            return request.Url.Host;
        }
      
         /// <summary>
        /// 获得当前完整Url地址
        /// </summary>
        /// <returns>当前完整Url地址</returns>
        public static string GetUrl()
        {
            return HttpContext.Current.Request.Url.ToString();
        }
        /// <summary>
        /// 返回指定的服务器变量信息
        /// </summary>
        /// <param name="strName">服务器变量名</param>
        /// <returns>服务器变量信息</returns>
        public static string GetServerString(string strName)
        {
            //
            if (HttpContext.Current.Request.ServerVariables[strName] == null)
            {
                return "";
            }
            return HttpContext.Current.Request.ServerVariables[strName].ToString();
        }
        /// <summary>
        /// 返回上一个页面的地址
        /// </summary>
        /// <returns>上一个页面的地址</returns>
        public static string GetUrlReferrer()
        {
            string retVal = null;
            try
            {
                retVal = HttpContext.Current.Request.UrlReferrer.ToString();
            }
            catch { }
            if (retVal == null)
                return "";
            return retVal;
        }
        /// <summary>
        /// 获得当前页面的名称
        /// </summary>
        /// <returns>当前页面的名称</returns>
        public static string GetPageName()
        {
            string[] urlArr = HttpContext.Current.Request.Url.AbsolutePath.Split('/');
            return urlArr[urlArr.Length - 1].ToLower();
        }
        /// <summary>
        /// 获取用户真实IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetUserIp()
        {
            string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (ip == null || ip.Length == 0 || ip.ToLower().IndexOf("unknown") > -1)
            {
                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                if (ip.IndexOf(',') > -1)
                {
                    ip = ip.Substring(0, ip.IndexOf(','));
                }
                if (ip.IndexOf(';') > -1)
                {
                    ip = ip.Substring(0, ip.IndexOf(';'));
                }
            }
            Regex regex = new Regex("[^0-9.]");
            if (ip == null || ip.Length == 0 || regex.IsMatch(ip))
            {
                ip = HttpContext.Current.Request.UserHostAddress;
                if (ip == null || ip.Length == 0 || regex.IsMatch(ip))
                {
                    ip = "0.0.0.0";
                }
            }
            return ip;
        }

        /// <summary>
        /// 获取Ip地址的计算值
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static Int64 GetIPNum(string ip)
        {
            if (HttpRuntime.Cache.Get(ip) != null)
            { return (long)HttpRuntime.Cache.Get(ip); }
            else
            {
                Int64 num = 0;
                string[] ips = ip.Split('.');
                num = Convert.ToInt64(ips[0]) * 256 * 256 * 256 + Convert.ToInt64(ips[1]) * 256 * 256 + Convert.ToInt64(ips[2]) * 256 + Convert.ToInt64(ips[3]) - 1;
                HttpRuntime.Cache.Insert(ip, num);
                return num;
            }
        }

        #region Cookie 操作
        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
            {
                return HttpContext.Current.Request.Cookies[strName].Value.ToString().Trim();
            }
            return "";
        }
        /// <summary>
        /// 读cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <returns>cookie值</returns>
        public static string GetCookie(string strName, string key)
        {
            if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
            {
                return HttpContext.Current.Request.Cookies[strName][key].ToString();
            }
            return "";
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        public static void WriteCookie(string strName, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>

        public static void WriteCookie(string strName, string key, string strValue)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie[key] = strValue;
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="expires">过期时间(分钟)</param>
        public static void WriteCookie(string strName, string strValue, int expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = DateTime.Now.AddMinutes(expires);
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 写cookie值
        /// </summary>
        /// <param name="strName">名称</param>
        /// <param name="strValue">值</param>
        /// <param name="expires">过期时间</param>
        public static void WriteCookie(string strName, string strValue, DateTime expires)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = strValue;
            cookie.Expires = expires;
            HttpContext.Current.Response.AppendCookie(cookie);
        }
        /// <summary>
        /// 删除cookie
        /// </summary>
        /// <param name="strName"></param>
        public static void RemoveCookie(string strName)
        {
            HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
            if (cookie == null)
            {
                cookie = new HttpCookie(strName);
            }
            cookie.Value = null;
            cookie.Expires = DateTime.Now.AddYears(-1);
            HttpContext.Current.Response.AppendCookie(cookie);
        }

        /// <summary>
        /// 清除所有的Cookies
        /// </summary>
        public static void RemoveAllCookies()
        {



            int limit = HttpContext.Current.Request.Cookies.Count;
            for (int i = 0; i < limit; i++)
            {

                RemoveCookie(HttpContext.Current.Request.Cookies[i].Name);
            }

        }

#endregion


        #region 字符操作过滤SQL

        /**/
        /// <summary>
        /// 过滤SQL
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string FilterSQL(string text)
        {
            string validSql = "";
            if (text != null)
            {
                text = text.Trim();
                text = text.Replace(";", "'';''");
                text = text.Replace("'", "''");
                text = text.Replace("--", "''--''");
                text = text.Replace("%25", "");
                text = text.Replace("%0a", "");
                text = text.Replace("%22", "");
                text = text.Replace("%27", "");
                text = text.Replace("%5c", "");
                text = text.Replace("%2f", "");
                text = text.Replace("%3c", "");
                text = text.Replace("%3e", "");
                text = text.Replace("%26", "");
                text = text.Replace("<", "&lt;");
                text = text.Replace(">", "&gt;");
                validSql = text;
            }
            return validSql;
        }



        public static string SafeRequest(string str)
        {
            string validSql = "";
            if (str != null)
            {
                str = str.Trim();
                str = str.Replace('\'', ' ');

                str = str.Replace("&nbsp;", "");
                str = str.Replace("\n;", "");
                validSql = str;
            }
            return validSql;
        }

        #endregion

    }
}
